package com.xcity.game.buildv2;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.xcity.db.entity.Employee;
import com.xcity.db.entity.Player;
import com.xcity.game.assist.AssistBuild;
import com.xcity.game.buildv2.BuildV2.State;
import com.xcity.game.buildv2.template.BuildTemplateV2;
import com.xcity.game.common.MessageConst;
import com.xcity.game.employee.EmployeeListener;
import com.xcity.game.io.SerializeStream;
import com.xcity.game.io.Serializer;
import com.xcity.game.io.SerializerUtils;
import com.xcity.game.player.cache.PlayerCacheService;
import com.xcity.pomelo.response.HintResponse;

import naga.x.App;
import naga.x.common.Updatable;
import naga.x.game.time.TimeUpdater;

public class BuildManagerV2 implements EmployeeListener, Serializer, Updatable{
	
	private long lastRemoveEmployeeTime;
	private long lastUpdateCapture;
	public static final int BUILD_ADD_EMPLOYEE_CD = 15000;//毫秒BuildV2.DEBUG?2000:
	public static final int BUILD_UPDATE_CD = 30 * 1000;
	public static final int BUILD_MAX_ASSISTANT_COUNT = 60;
	protected Player owner;
	protected List<BuildV2> buildings;
	
	protected int lastAssistDay;//上一次邀请好友协防的day
	
	protected List<Long> assitants;//今天被邀请协防的PlayerID
	
	public BuildManagerV2() {}

	public BuildManagerV2(Player player, List<BuildV2> buildings, int lastAssDay, List<Long> assList) {
		this.owner = player;
		if (buildings == null) {
			buildings = new ArrayList<BuildV2>();
		}
		for (int i = buildings.size() - 1; i >= 0; i--) {
			BuildV2 building = buildings.get(i);
			building.vm = this;
			building.init();
		}
		this.buildings = buildings;
		State s;
		if (buildings.isEmpty() // 初始化第一个建筑
				|| (s = getLast().getState()) == State.BUILT // 策划新加建筑
				|| s == State.CAPTURED) {
			createNextBuilding();
		}
		this.assitants = assList != null? assList : new ArrayList<Long>();
		this.lastAssistDay = lastAssDay;
	}
	
	public Player getOwner() {
		return owner;
	}
	
	public void setOwner(Player player) {
		this.owner = player;
	}
	
	public List<BuildV2> getBuildings() {
		return buildings;
	}
	
	public int size() {
		return buildings.size();
	}
	
	public BuildV2 createNextBuilding() {
		BuildServiceV2 service = App.getApp().getServiceManager().get(BuildServiceV2.class);
		BuildTemplateV2 template = service.getTemplate(size());
		if (template != null) {
			BuildV2 b = new BuildV2(this, template);
			buildings.add(b);
			return b;
		}
		return null;
	}
	
	public BuildV2 find(int id) {
		List<BuildV2> list = buildings;
		for (int i = list.size() - 1; i >= 0; i--) {
			BuildV2 b = list.get(i);
			if (id == b.id) {
				return b;
			}
		}
		return null;
	}
	
	public BuildV2 getLast() {
		return buildings.get(buildings.size() - 1);
	}

	/**
	 * 遍历build查看哪个是assistant占的
	 * @param assistant
	 * @return
	 */
	public BuildV2 getAssistBuildByAssistant(long assistant){
		BuildV2 build = null;
		for(int i = 0, size = buildings.size(); i < size; i++){
			BuildV2 tmpBuild = buildings.get(i);
			if(tmpBuild.assistId == assistant){
				build = tmpBuild;
				break;
			}
		}
		return build;
	}
	
	public int tryTakeAllMoney(){
		int total = 0;
		for(int i = 0, size = buildings.size(); i < size; i++){
			BuildV2 build = buildings.get(i);
			if(build.getState() == State.BUILT){
				String str = build.takeMoney(true, false);
				if(str == null){
					total += build.lastTakeMoney;
				}
			}else if(build.getState() == State.ASSISTED){
				//协助建筑的话计算协助人的员工和时间
				Player assistant = App.getApp().getServiceManager().get(PlayerCacheService.class).find(build.getAssistId());
				if(assistant != null){
					long now = TimeUpdater.getInstance().now();
					AssistBuild assbuild = assistant.getAssists().findByOwnerId(owner.getId());
					if(assbuild != null){
						int[] takes = assbuild.takeMoney(assistant, now, build, false);
						total += takes[0];
					}
				}
			}
		}
		return total;
	}
	
	@Override
	public void fireEmployeeRemoved(Employee employee) {
		com.xcity.db.entity.Employee.State state = com.xcity.db.entity.Employee.State.DEFENSE;
		if (state.enable && employee.getState() != state) {
			return;
		}
		for (int i = 0, size = buildings.size(); i < size; i++) {
			BuildV2 b = buildings.get(i);
			int pos = b.removeEmployee(employee, null);
			if (pos >= 0) {
				break;
			}
		}
	}
	
	/**
	 * 如果记录上次协助时间不是今天 则置成今天并清空
	 * @param today
	 */
	public void tryResetAssist(int today){
		if(today != lastAssistDay){
			lastAssistDay = today;
			assitants.clear();
		}
	}
	
	public void resetAssist(){
		lastAssistDay = TimeUpdater.getInstance().today();
		assitants.clear();
	}
	
	/**
	 * 检查ID是否在今日协助列表里(不会判断时间合法性,需要之前判断)
	 */
	public boolean checkIsAssist(long pid){
		for(int i = 0, size = assitants.size(); i < size; i++){
			long tmp = assitants.get(i);
			if(tmp == pid){
				return true;
			}
		}
		return false;
	}
	
	public boolean checkIsMaxAssist(){
		if(assitants.size() >= BUILD_MAX_ASSISTANT_COUNT){
			return true;
		}
		return false;
	}
	
	public int getAssSize(){
		return assitants.size();
	}
	
	public void addNewAssistantId(long pid){
		assitants.add(pid);
	}
	
	@Override
	public String toString() {
		return JSON.toJSONString(buildings) + ";" + JSON.toJSONString(lastAssistDay) + ";" + JSON.toJSONString(assitants);
	}
	
	/**
	 * 加员工是否在CD
	 * @return true在CD  false不在
	 */
	public int checkInCD(){
		int ret = 0;
//		if(lastRemoveEmployeeTime + BUILD_ADD_EMPLOYEE_CD > TimeUpdater.getInstance().now() ){
//			ret = true;
//		}
		ret = (int) ((lastRemoveEmployeeTime + BUILD_ADD_EMPLOYEE_CD - TimeUpdater.getInstance().now()) / 1000);
		return ret;
	}
	
	public void resetLastRemoveEmployeeTime(){
		lastRemoveEmployeeTime = TimeUpdater.getInstance().now();
	}

	@Override
	public void write(SerializeStream out) {
		SerializerUtils.serialize(this, out);
	}

	@Override
	public boolean update() {
		long now = TimeUpdater.getInstance().now();
		if(now > lastUpdateCapture){
			lastUpdateCapture = now + BUILD_UPDATE_CD;
			for(int i = 0; i < buildings.size(); i++){
				BuildV2 build = buildings.get(i);
				if(build.getState() == State.CAPTURED){
					build.update();
				}else if(build.getState() == State.ASSISTED){
					build.updateAssist();
				}
			}
		}
		return true;
	}
}
